package kr.hkit.password.fragment.account;

import kr.hkit.password.R;
import kr.hkit.password.dao.InfoDao;
import kr.hkit.password.db.MyDatabaseManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AccountLogin extends Fragment implements OnClickListener {
	private static final String TAG = "PW";
	private MyDatabaseManager mAdb;
	private EditText tv1;
	private EditText tv2;
	private InfoDao info;
	private Fragment fragment;
	private FragmentManager frgManager;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.d(TAG, "Login onCreateView");
		
		View view = inflater.inflate(R.layout.account_login, container, false);
		mAdb = MyDatabaseManager.getInstance(getActivity());
		info = (InfoDao) getActivity().getApplication();
		tv1 = (EditText) view.findViewById(R.id.tvAc);
		tv2 = (EditText) view.findViewById(R.id.tvPw);
		Button btn = (Button) view.findViewById(R.id.btnLogin);
		btn.setOnClickListener(this);
		Button btn2 = (Button) view.findViewById(R.id.btnFindPw);
		btn2.setOnClickListener(this);
		Button btn3 = (Button) view.findViewById(R.id.btnNewAc);
		btn3.setOnClickListener(this);
		return view;
	}
	
	@Override
	public void onClick(View v) {
		Log.d(TAG, "Login OnClick");
		
		switch (v.getId()) {
		case R.id.btnLogin:
			String[] args = { tv1.getText().toString(),
					tv2.getText().toString() };
			Cursor rs = mAdb.select("account", new String[] { "account", "alarm" },
					"account=? and password=?", args, null, null, null);

			if (rs != null && rs.moveToNext()) {
				getActivity().getActionBar().show();
				String ac = rs.getString(0);
				Toast.makeText(getActivity(), ac + " Login!!", Toast.LENGTH_LONG).show();
				info.setAlarmUse((rs.getInt(1)==1)?true:false);
				info.setAccount(ac);
				info.setLogin(true);
				fragment = new AccountView();
				frgManager = getFragmentManager();
				frgManager.beginTransaction().replace(R.id.content_frame, fragment)
						.commit();
			} else {
				Toast.makeText(getActivity(), "로그인 실패!!", Toast.LENGTH_LONG)
						.show();
			}
			rs.close();
			break;
		case R.id.btnFindPw:
			fragment = new AccountSearch();
			frgManager = getFragmentManager();
			frgManager.beginTransaction().replace(R.id.content_frame, fragment)
					.commit();
			break;
		case R.id.btnNewAc:
			fragment = new AccountCreate();
			frgManager = getFragmentManager();
			frgManager.beginTransaction().replace(R.id.content_frame, fragment)
					.commit();
			break;
		}
	}
}
